package com.fxc.handler;

import com.fxc.MySQLRemoteService;
import com.fxc.config.OBSProperties;
import com.fxc.crowd.constant.CrowdConstant;
import com.fxc.crowd.util.CrowdUtil;
import com.fxc.crowd.util.ResultEntity;
import com.fxc.entity.VO.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author FXC
 * @version 1.0
 * @date 2021/12/10 20:52
 */
@Controller
public class ProjectConsumerHandler {

    @Autowired
    private OBSProperties obsProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    @RequestMapping("/get/project/derail/{projectId}")
    public String getProjectDerail(@PathVariable("projectId") Integer projectId, Model model){

        ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.getProjectDetailRemote(projectId);

        if (ResultEntity.SUCCESS.equals(resultEntity.getResult())){
            DetailProjectVO data = resultEntity.getData();

            model.addAttribute("detailProjectVO", data);
        }

        return "project-show-detail";
    }

    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile returnPicture) throws IOException {
        return CrowdUtil.uploadFileToObs(
                obsProperties.getEndPoint(),
                obsProperties.getAk(),
                obsProperties.getSk(),
                returnPicture.getInputStream(),
                obsProperties.getBucketName(),
                returnPicture.getOriginalFilename()
        );


    }

    @RequestMapping("/create/confirm")
    public String saveConfirm(HttpSession session, MemberConfirmInfoVO memberConfirmInfoVO, ModelMap modelMap){

        // 1.从session域读取之前临时存储的ProjectVO的对象
        ProjectVO projectVO = (ProjectVO)session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        // 2.如果projectVO == null
        if (projectVO == null){
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
        }

        // 3.将确认信息数据设置到projectVO对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 4.从session域读取当前用户
        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        Integer memberId = memberLoginVO.getId();

        // 5.调用远程的方法，将数据发送给mysql-provider
        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO, memberId);

        // 6.判断远程的保存是否成功
        String result = saveResultEntity.getResult();
        if (ResultEntity.FAILED.equals(result)){

            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, saveResultEntity.getMessage());

            return "project-confirm";
        }

        // 7.将临时的ProjectVO 对象从session域中移除
        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        // 8.如果远程保存成功则跳转到最终完成的页面
        return "redirect:http://localhost:8081/project/create/success";
    }

    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession session){

        try {
            // 1.从session域中读取之前缓存的ProjectVO对象
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

            // 2，判断ProjectVo是否为null
            if(projectVO == null){
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
            }

            // 从ProjectVO对象中获取存储汇报信息合集
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

            // 判断集合是否有效
            if (returnVOList == null || returnVOList.size() == 0){

                // 创建集合对象对returnVOList进行初始化
                returnVOList = new ArrayList<>();


                // 为了能够正常使用这个集合，设置到projectVO对象中
                projectVO.setReturnVOList(returnVOList);

            }

            // 将收集了表单数据的returnVO对象存入集合
            returnVOList.add(returnVO);

            // 8.把数据有变化的projectVO对象重新存入Session域，以确保新的数据最终能够存入redis
            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);

            // 所以操作成功后返回成功
            return ResultEntity.successWithData();
        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.failed(e.getMessage());
        }
    }

    /**
     * todo：待优化图片上传用户体验不好
     * 一次失败则全部重新再来
     * 需要加入分布式事务
     * @param projectVO
     * @param headerPicture
     * @param detailPictureList
     * @param session
     * @param modelMap
     * @return
     */
    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(
            // 接收除了上传图片之外的普通数据
            ProjectVO projectVO,

            // 接收上传的头图
            MultipartFile headerPicture,

            // 接收上传详情的图片
            List<MultipartFile> detailPictureList,

            // 用来收集一部分数据的ProjectVO对象存入session
            HttpSession session,

            // 用来在当前操作失败后返回上一个表单页面时携带提示消息
            ModelMap modelMap
    ) throws IOException {


        // 完成头图的上传
        boolean heardPictureIsEmpty = headerPicture.isEmpty();

        String result;

        if (heardPictureIsEmpty){

            // 6. 如果上传没有头图则返回到表单页面并显示错误信息
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);

            return "project-launch";
        }


        // 上传图片
            ResultEntity<String> uploadResultEntity = CrowdUtil.uploadFileToObs(
                    obsProperties.getEndPoint(),
                    obsProperties.getAk(),
                    obsProperties.getSk(),
                    headerPicture.getInputStream(),
                    obsProperties.getBucketName(),
                    headerPicture.getOriginalFilename()
            );

            //获取返回结果
            result = uploadResultEntity.getResult();

            // 2.判断是否上传成功
            if(ResultEntity.SUCCESS.equals(result)){

                // 获取图片访问路径
                String headerPicturePath = uploadResultEntity.getData();

                projectVO.setHeaderPicturePath(headerPicturePath);
            }else{

                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);

                return "project-launch";
            }

        // 如果用户确实上传了有内容的文件，则执行上传
        // 3.用于收集详情图片
        ArrayList<String> detailUploadResults = new ArrayList<>();
        // 详情图片不可为空
        if(detailPictureList == null || detailPictureList.size() == 0){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
            return "project-launch";
        }

        for (MultipartFile multipartFile : detailPictureList){
            if (multipartFile.isEmpty()){
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
                return "project-launch";
            }

            // 上传图片
            ResultEntity<String> detailUploadResultEntity = CrowdUtil.uploadFileToObs(
                    obsProperties.getEndPoint(),
                    obsProperties.getAk(),
                    obsProperties.getSk(),
                    multipartFile.getInputStream(),
                    obsProperties.getBucketName(),
                    multipartFile.getOriginalFilename()
            );

            result = detailUploadResultEntity.getResult();

            if(ResultEntity.SUCCESS.equals(result)){

                // 将单个上传成功的图片路径存入集合
                detailUploadResults.add(detailUploadResultEntity.getData());
            }else{
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                return "project-launch";
            }

        }

        // 将存放了详情图片访问路径的集合存入ProjectVO中
        projectVO.setDetailPicturePathList(detailUploadResults);

        // 将ProjectVO对象存入Session域
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);

        // 以完整的访问路径前往下一个收集回报的信息页面
        return "redirect:http://localhost:8081/project/return/info/page";
    }
}
